import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Benutzer;
import model.artikelListe;
import model.Artikel;
import dao.ArtikelDAO;
import model.benutzerListe;
import dao.BenutzerDAO;
import controller.ArtikelController;
import controller.BenutzerController;

/**
 * Servlet implementation class Main
 */
public class Main extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Main() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(arg0, arg1);

	}

	static void Update(HttpServletRequest request, HttpServletResponse response, ServletContext context) {
		ArtikelDAO dao = new ArtikelDAO();
		artikelListe allArtikel = null;

		try {
			allArtikel = dao.getAllArtikel();
		} catch (SQLException e) {
			showError("Fehler!", e.getMessage(), request, response, context);
			return;
		}

		Date d = new Date(System.currentTimeMillis());

		for (Artikel a : allArtikel) {
			String status = a.get_status();

			if (!status.equals("verkauft")) {
				if (a.get_startdatum().before(d) && a.get_enddatum().after(d)) {
					status = "offen";
				} else if (d.after(a.get_enddatum())) {
					if (a.get_kaeufer().equals("")) {
						status = "nicht verkauft";
					} else {
						status = "verkauft";
					}
				} else {
					status = "geschlossen";
				}

				a.set_status(status);

				try {
					dao.saveArtikel(a);
				} catch (SQLException e) {
					showError("Fehler!", e.getMessage(), request, response, context);
				}
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Update(request, response, getServletContext());

		HttpSession session = request.getSession(true);
		String action = request.getParameter("action");

		if (action != null) {
			ArtikelDAO d = new ArtikelDAO();
			try {
				artikelListe liste = d.getAllArtikel();
				session.setAttribute("artikelListe", liste);

				try {
					Benutzer b = (Benutzer) session.getAttribute("benutzer");
				} catch (Exception e) {

				}
				if (action.equals("Verkaufen") && session.getAttribute("benutzer") != null) {
					Benutzer b = (Benutzer) session.getAttribute("benutzer");
					artikelListe al = new artikelListe();
					for (Artikel a : liste) {
						if (a.get_verkaeufer().equals(b.get_Benutzername())) {
							al.add(a);
						}
					}

					session.setAttribute("verkauefe", al);
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Benutzerseite.jsp");
					dispatcher.include(request, response);
					return;
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (action != null && action.equals("logout")) {
				session.setAttribute("loggedIn", "false");
				session.removeAttribute("benutzer");
			}
		}

		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
		dispatcher.include(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Update(request, response, getServletContext());
		HttpSession session = request.getSession(true);
		String action = request.getParameter("action");
		BenutzerController BenCon = new BenutzerController();
		ArtikelController cont = new ArtikelController();
		Benutzer b = null;

		if (action != null) {
			if (action.equals("Registrierung")) {
				String _Vorname = request.getParameter("reg_vorname");
				String _Nachname = request.getParameter("reg_nachname");
				String _Geburtstag = request.getParameter("reg_geburtstag");
				String _Email = request.getParameter("reg_email");
				String _Benutzername = request.getParameter("reg_username");
				String _Passwort = request.getParameter("reg_passwort");
				String _wPw = request.getParameter("reg_passwortWiederholung");
				if(_Passwort.equals("")||_wPw.equals(""))
				{
					showError("Fehler!", "Passwort ist falsch!", request, response, getServletContext());
					return;
				}
				try {
					if (BenCon.registrieren(_Vorname, _Nachname, _Geburtstag, _Email, _Benutzername, _Passwort, _wPw)) {
						b = BenCon.login(_Benutzername, _Passwort);
					}
				} catch (Exception e) {

					e.printStackTrace();
				}
				if (b != null) {
					//
					session.setAttribute("loggedIn", "true");
					session.setAttribute("benutzer", b);
				} else {
					session.setAttribute("loggedIn", "false");
				}
			} else if (action.equals("Login")) {
				String _Benutzername = request.getParameter("username");
				String _Passwort = request.getParameter("passwort");
				try {
					b = BenCon.login(_Benutzername, _Passwort);	
				} catch (Exception e) {
				}
				if (b != null) {
					//
					session.setAttribute("loggedIn", "true");
					session.setAttribute("benutzer", b);
				} else {
					session.setAttribute("loggedIn", "false");
					session.setAttribute("wrongCredentials", new Boolean(true));
				}
			} else if (action.equals("Suchen")) {                                 
				String _name = request.getParameter("bsuche");
				String _kategorie = request.getParameter("bkategorie");
				artikelListe a = null;

				try {
					a = cont.Artikel_suchen(_name, _kategorie);
				} catch (SQLException e) {
					e.printStackTrace();
				}

				try {
					b = (Benutzer) session.getAttribute("benutzer");
				} catch (Exception e) {
				}
				
				if (a != null) {
					request.setAttribute("verkauefe", a);
				}
				
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(b == null || b.get_Benutzername() == null ? "/index.jsp" : "/Benutzerseite.jsp");
				dispatcher.include(request, response);
				
				return;
			}

			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Benutzerseite.jsp");
			dispatcher.include(request, response);
		}
	}

	static void showError(String errorTitle, String errorMsg, HttpServletRequest request, HttpServletResponse response, ServletContext context) {
		request.setAttribute("errorTitle", errorTitle);
		request.setAttribute("errorMsg", errorMsg);

		RequestDispatcher dispatcher = context.getRequestDispatcher("/error.jsp");

		try {
			dispatcher.include(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
